package com.example.service;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.jwt.JwtTokenUtils;
import com.example.dao.ImSingleMapper;
import com.example.entity.ImSingle;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ImSingleService extends ServiceImpl<ImSingleMapper, ImSingle> {

    @Autowired
    private UserService userService;


    public List<User> findUser(String fromUser) {
        System.out.println("fromUser");

        // 1. 查询所有聊天记录
        List<ImSingle> chatRecords = this.list(new QueryWrapper<ImSingle>()
                .eq("fromuser", fromUser)
                .or().eq("touser", fromUser));

        // 2. 提取 toUser 字段并去重
        List<String> toUsers = chatRecords.stream()
                .map(imSingle -> removePrefix(imSingle.getTouser()))
                .filter(Objects::nonNull) // 确保不会有 null 值
                .distinct()
                .collect(Collectors.toList());

        System.out.println("提取的 toUsers：" + toUsers);

        // 3. 为空时直接返回空列表，避免查询所有用户
        if (toUsers.isEmpty()) {
            return Collections.emptyList();
        }

        // 4. 查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("name", toUsers);

        return userService.list(queryWrapper);
    }

    // 去除前缀的通用方法
    private String removePrefix(String toUser) {
        if (toUser.startsWith("STUDENT_")) {
            return toUser.replace("STUDENT_", "");
        } else if (toUser.startsWith("ADMIN_")) {
            return toUser.replace("ADMIN_", "");
        } else if (toUser.startsWith("TEACHER_")) {
            return toUser.replace("TEACHER_", "");
        }else if (toUser.startsWith("null_")) {
            return toUser.replace("null_", "");
        }
        return toUser;  // 如果没有匹配的前缀，返回原始用户名
    }

    // 使用ServiceImpl的通用方法插入数据
    public ImSingle add(ImSingle imSingle) {
        this.save(imSingle); // MyBatis-Plus 提供的插入方法
        return imSingle;
    }

    // 查找与某个用户的聊天记录，并更新未读标记
    public List<ImSingle> findByUsername(String fromUser, String toUser) {
        List<ImSingle> list = this.list(new QueryWrapper<ImSingle>().eq("fromuser", fromUser).eq("touser", toUser));
        list.forEach(x -> {
            if (x.getTouser().equals(fromUser) && x.getFromuser().equals(toUser)) {
                x.setReaded(1);
                this.updateById(x); // 使用MyBatis-Plus的更新方法
            }
        });
        return list;
    }
    public List<ImSingle> findByGroupId( Integer groupId) {
        User currentUser = JwtTokenUtils.getCurrentUser();
        Integer currentUserId = currentUser.getId();
        List<ImSingle> list = this.list(new QueryWrapper<ImSingle>().
                eq("to_group_id", groupId)
                .eq("is_to_group", 1));
//        User currentUser = JwtTokenUtils.getCurrentUser();
        Integer userId =  currentUserId;

        list.forEach(x -> {
            String readGroupUserIdStr = x.getReadGroupUserId(); // 获取字符串

            // 防止空指针异常，确保字符串格式正确
            List<Integer> readUserIds = (readGroupUserIdStr == null || readGroupUserIdStr.isEmpty())
                    ? new ArrayList<>() // 为空则创建新列表
                    : Arrays.stream(readGroupUserIdStr.split(",")) // 分割字符串
                    .filter(s -> !s.isEmpty()) // 避免空元素
                    .map(Integer::parseInt) // 转换为 Integer
                    .collect(Collectors.toList());

            // 如果 readUserIds 不包含 userId，则添加并更新
            if (!readUserIds.contains(userId)) {
                readUserIds.add(userId);
                x.setReadGroupUserId(readUserIds.stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(","))); // 转回字符串存储

                this.updateById(x); // MyBatis-Plus 更新数据库
            }
        });



        return list;
    }

    // 查找未读消息的数量
    public Dict findUnReadNums(String toUsername) {
        List<ImSingle> list = this.list(new QueryWrapper<ImSingle>().eq("touser", toUsername));
        Map<String, List<ImSingle>> collect = list.stream().collect(Collectors.groupingBy(ImSingle::getFromuser));
        Dict dict = Dict.create();
        collect.forEach((k, v) -> dict.set(k, v.size()));
        return dict;
    }
}
